/*
 * Copyright 2018 the original author or authors.
 * 
 * you can use the file or import project.but Do not take legal responsibility.
 * Only for learning communication.
 *
 * Java compiled version 1.8 or higher
 * 
 * 
 * 
 * 
 */
package org.liang.downimage.core;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.LinkedList;
import java.util.Queue;

import org.liang.downimage.config.AppConfig;
import org.liang.downimage.util.CheckUtil;

/**
 * 多线程下载图片的核心类
 * @author houliang
 * @date 2018年1月27日
 */
public class DownImageThread implements Runnable{

	/**保存图片地址进行下载，下载后删除*/
	private Queue<String> imgUrls = new LinkedList<String>();
	/**统计下载图片的数量*/
	public static int imgNum=0;
	
	@Override
	public void run() {
		
		while(imgUrls.size() > 0) {
			String imgUrl = imgUrls.poll();
			downOneImg(imgUrl);
		}
	}
	
	/**
	 * 初始化图片网络地址队列
	 * @param imgUrls
	 */
	public void initUrl(Queue<String> imgUrls) {
		if(imgUrls != null && imgUrls.size() >0) {
//			for(int i=0;i<imgUrls.size();i++) {
//				
//				this.imgUrls.addAll(imgUrls.);
//			}
			this.imgUrls.addAll(imgUrls);
		}
	}
	
	/**
	 * 根据图片地址下载图片并保存
	 * @param imgUrl 图片网络地址
	 */
	private void downOneImg(String imgUrl) {
		if(!CheckUtil.checkDir()) {
			return;
		}
		
		try {
			int num = imgNum++;//防止多线程高并发导致数据错乱
			URL url = new URL(imgUrl);
			//链接网络地址  
			HttpURLConnection connection = (HttpURLConnection)url.openConnection();  
			//获取链接的输出流  
			InputStream is = connection.getInputStream(); 
			int n = imgUrl.lastIndexOf(".");
			
			int t = imgUrl.lastIndexOf("/");

			String type = imgUrl.substring(n);
			String name=num+imgUrl.substring(t+1, n)+""+type;
			
			String downPath = AppConfig.savePath + "\\" + name;
			FileOutputStream out = new FileOutputStream(downPath);
			
			byte[] b = new byte[512];
			int x=-1;
			while((x=is.read(b))>0) {
				out.write(b,0,x);
			}
			out.close();
			is.close();
			System.out.println("保存图片："+num+";"+downPath);

		} catch (Exception e) {
			System.out.println("错误链接：" +imgUrl);
			e.printStackTrace();
		}  
	}
}
